import { RECORD_USERINFO, GET_USERINFO } from './mutation-types';
import { setItem } from '../utils/storage';
import { fetchUser } from '../api/user';

export default {
    namespaced: true,
    state: {
        userInfo: '',
        isLogin: true
    },
    mutations: {
        // 记录用户信息
        [RECORD_USERINFO](state, info) {
            state.userInfo = info;
            state.isLogin = true;
            setItem('user_id', info.user_id);
        },
        // 获取用户信息存入 vuex
        [GET_USERINFO](state, info) {
            if (state.userInfo && state.userInfo.username !== info.username) {
                return;
            }
            if (!state.login) {
                return;
            }
            if (!info.message) {
                state.userInfo = { ...info };
            } else {
                state.userInfo = null;
            }
        }
    },
    actions: {
        async getUserInfo({ commit }) {
            let res = await fetchUser();
            commit(GET_USERINFO, res);
        }
    }
};
